package com.cjm.one.common.interceptor;

import com.cjm.one.common.constant.SecurityConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;

@Slf4j
public class OneRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("feign 拦截器");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String fromSource = request.getHeader(SecurityConstants.FROM_SOURCE);

            log.info("请求地址：{}",request.getRequestURL());
            log.info("请求类型：{}",request.getMethod());
            if (StringUtils.hasText(fromSource) && SecurityConstants.INNER.equals(fromSource)) {
                log.info("内部调用不传递token");
                return;
            }
            log.info("Original URI: {}", request.getRequestURI());
            // 非web 请求直接跳过
//            if (Optional.ofNullable(request).isPresent()) {
//                return;
//            }

            String token = request.getHeader("Authorization");
            log.info("传递token:{}", token);
            requestTemplate.header("Authorization", token);

        }

    }
}